package com.lzh.file.task;

import com.lzh.file.entity.FileInfo;
import com.lzh.file.service.IFileService;
import com.lzh.runke.core.task.AbstractTask;
import com.lzh.runke.core.web_base.helper.DateHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * 文件清理定时任务
 *
 * @author linmeijie
 * @date 2019-7-4
 */
@Slf4j
@Component
public class FileCleanupTask extends AbstractTask {

    @Resource
    private IFileService fileService;

    /**
     * 每天 0:15:00:000 清理 前一天 00:00:00:000 至 今天 00:00:00:000 未关联业务表的文件及文件数据
     */
    @Scheduled(cron = "0 15 0 * * ?")
    public void fileCleanupTask() {
        if (!enableTask) {
            return;
        }

        try {
            LocalDateTime now = LocalDateTime.now();
            //获取今天的开始时间和结束时间
            Date fromDateTime = DateHelper.asDate(now.withHour(0).withMinute(0).withSecond(0).withNano(0));
            Date toDateTime = DateHelper.asDate(now.withHour(23).withMinute(59).withSecond(59).withNano(999999999));

            log.info("现在开始清理" + fromDateTime + " - " + toDateTime + "未关联业务表的文件及相关信息");

            List<FileInfo> fileInfos = fileService.loadUnRelatedFilenames(fromDateTime, toDateTime);
            log.info("找到" + fileInfos.size() + "条数据，被清理的文件名：");

            fileInfos.parallelStream().forEach(fileInfo -> {
                log.info(fileInfo.toString());
                fileService.deleteUploaded(fileInfo.getFilename());
            });

            log.info("文件清理结束。");
        } catch (Exception e) {
            log.error("AsyncProfiledThread got an Exception:", e);
        }
    }
}
